import React, { lazy, FC, useMemo } from 'react'
import { useLocation, Redirect } from 'react-router-dom';
import { API } from 'App.d'
import { Route } from 'react-router-dom';

interface IProps {
  routes: Array<API.IRoute>
}

const DynamicRoutes: FC<IProps> = (props) => {

  /* 根据路由表找出当前路由信息 */
  const getCurrentRoute = (routes: Array<API.IRoute>, currentPath: string): any => {
    let target: API.IRoute | undefined
    for (let i = 0; i < routes.length; i++) {
      const route = routes[i]
      if (route.path === currentPath) {
        return target = route
      }

      if (route.routes) {
        target = getCurrentRoute(route.routes, currentPath)
        if (target) {
          return target
        }
      }
    }
  }

  const { pathname: currentPath } = useLocation() //取出当前pathname
  const currentRoute = getCurrentRoute(props.routes, currentPath) // 根据当前路径到路由表找出路由信息
  const Component = lazy(() => import(/* webpackChunkName:"[request]" */`pages/${currentRoute.component.slice(8)}`))

  return (
    currentRoute ?
      <Route path={currentRoute.path} component={Component} exact />
      : <Redirect to="/404"></Redirect>
  )
}

export default DynamicRoutes